package com.example.cloudcommon.event.stream;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class ScheduledEventPublisher {

    @Autowired
    private EventStreamService eventStreamService;

    private int counter = 0;

    /**
     * 每5秒发送一次心跳事件
     */
    @Scheduled(fixedRate = 5000)
    public void sendHeartbeat() {
        Map<String, Object> heartbeat = new HashMap<>();
        heartbeat.put("type", "heartbeat");
        heartbeat.put("timestamp", new Date());
        heartbeat.put("counter", counter++);

        eventStreamService.broadcast(EventStream.of("heartbeat", heartbeat));
    }

    /**
     * 每30秒发送系统状态
     */
    @Scheduled(fixedRate = 30000)
    public void sendSystemStatus() {
        Runtime runtime = Runtime.getRuntime();
        Map<String, Object> status = new HashMap<>();
        status.put("freeMemory", runtime.freeMemory());
        status.put("totalMemory", runtime.totalMemory());
        status.put("maxMemory", runtime.maxMemory());
        status.put("availableProcessors", runtime.availableProcessors());

        eventStreamService.broadcast(EventStream.of("system-status", status));
    }
}